package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Member;
import com.itheima.utils.MD5Utils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
    @Resource
    private MemberDao memberDao;

    @Resource
    private OrderDao orderDao;
    //根据月份查询会员数量
    @Override
    public List<Integer> findMemberByMonths(List<String> months) {
        List<Integer> list = new ArrayList<>();
        for (String month : months) {
            month = month+".31";
            Integer count = memberDao.findMemberCountBeforeDate(month);
            list.add(count);
        }
        return list;
    }

    //根据手机号查询会员
    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    //新增会员
    @Override
    public void add(Member member) {
        if (member.getPassword()!=null){
            member.setPassword(MD5Utils.md5(member.getPassword()));
        }
        memberDao.add(member);
    }

    //修改会员
    @Override
    public void editMember(Member member) {

        memberDao.edit(member);
    }





    /**
     * 会员分页查询
     * @param queryPageBean
     * @return
     */
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Member> page = memberDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 删除会员
     * @param id
     */
    public void deleteById(Integer id) {
        long count = memberDao.findCountByMemberId(id);
        if (count > 0) {
            new RuntimeException();
            orderDao.deleteByMemberId(id);
        }
        memberDao.deleteById(id);
    }


    /**
     * 回显
     * @param id
     * @return
     */
    public Member findById(Integer id) {
        return memberDao.findById(id);
    }


    /**
     * 编辑
     * @param member
     */
    public void edit(Member member) {
        memberDao.edit(member);
    }


}
